<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Jquery测试</title>
<script src="js/jquery-3.2.1.min.js"></script>
<style>
	.pcls:hover{
		background-color: #4984FD;
		cursor: pointer;
	}

</style>
		
</head>
<body>
<div id="container">
	<div id="input" style="width: 300px;">
		输入省份：<input id="inp" type="text" name="province" /><button id="queryBtn">查询</button>
	</div>
	<div id="tip" style="border:1px solid black; width: 300px; height:300px; overflow:scroll; margin-top: 5px; display:none;">
	</div>

</div>
	<script type="text/javascript">
		$(function(){
			var url = "http://localhost:8090/ajaxdemo/province/query";
			var render = renderFactory();
			var target = $("#tip");
			var queryBtn = $("#queryBtn");
			var inp = $("#inp");
			$(queryBtn).click(function(){
				var text = $(inp).val();
				queryProvinces(url,text,function(data){
					render.render(target, data);
					render.addEvent("pcls","click",pClickEvent);
				});
			});
			
			$(inp).keyup(function(){
				var text = $(inp).val();
				queryProvinces(url,text,function(data){
					render.render(target, data);
					render.addEvent($(".pcls"),"click",pClickEvent);
				});
			});
			
			$(inp).focus(function(){
				$(target).show();
			});
			
			//查询省份
			function queryProvinces(url, name,fn){
				let reg = /^[\u4e00-\u9fa5]$/;
				if(name!=undefined){
					if(reg.test(name)){
						url = url+"?province="+encodeURIComponent(name);
					}else{
						url = url+"?province="+name;
					}
				}
				$.get(url,function(data){
					fn(data);
				});
			}
			
			//p添加事件
			function pClickEvent(){
				var text = $(this).html();
				$(inp).val(text);
			}
			
			//渲染工厂
			function renderFactory(){
				var o = {};

				//清楚Target上的子元素
				o.removeChild = function(target){		 
					$(target).children().remove();
				}

				//渲染指定Target
				o.render = function(target,data){
					if(Array.isArray(data)){
						this.removeChild(target);
						data.forEach((item,index,ary)=>{
							var pNode = $("<p></p>");
							$(pNode).attr("class","pcls");
							$(pNode).html(item.province);
							$(target).append(pNode);
						});
					}
				}
				
				//渲染后添加事件
				o.addEvent = function(target, event, fn){
					$(target).bind(event,fn);
				}
				return o;
			}
		});
	</script>
</body>
</html>